package control;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.HolidayDTO;
import business.HolidayManager;

public class AddHolidayServlet extends HttpServlet{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public AddHolidayServlet()
	{
		super();
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			processRequest(request, response);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}  	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			processRequest(request, response);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} 
	private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException {

		HolidayManager hm = new HolidayManager();
		HolidayDTO holiday= new HolidayDTO();
		
		Map<String, String> errors = new HashMap<String, String>();
		
		String origin = request.getParameter("holidayname");
		String origin2 = request.getParameter("timestamp");
		
		if (origin.isEmpty()) {
			errors.put("origin", "Enter Holiday Name");
		}else
		{
			 errors.remove("origin2");
		}
		if (origin2.isEmpty()) {
			errors.put("origin2", "Enter Holiday Date");
		}else
		{
			 errors.remove("origin2");
		}
		if (errors.isEmpty()) {
				
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				Date dStart = df.parse(request.getParameter("timestamp"));
				holiday.setHolidayName(request.getParameter("holidayname"));
				holiday.setHolidayDate(dStart);
				hm.insertHoliday(holiday);
				
				ArrayList<HolidayDTO> data = hm.findAllHoliday();
				request.setAttribute("holidays", data);
				RequestDispatcher rd = request.getRequestDispatcher("LoadHoliday.jsp");
			try {
				rd.forward(request, response);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		} else {
			request.setAttribute("errors", errors);
	        request.getRequestDispatcher("AddHoliday.jsp").forward(request, response);
	       
		}
}
}
